<?php

namespace app\api\controller;

use app\api\model\mysql\MallAccountLog;
use app\api\model\mysql\MallOrder;
use app\api\model\mysql\MallOrderGoods;
use app\api\model\mysql\MallSetting;
use app\api\model\mysql\MallUser;
use app\api\model\mysql\MallWithdrawal;
use app\common\lib\ArrClass;
use app\common\lib\Show;
use app\common\lib\Status;
use app\common\lib\Str;
use app\common\model\MallCommissionLevel;
use think\facade\Log;

class Commission extends Base
{
    /**
     * 我的直推会员（直接分享）
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function myTeamLevelUser(){
        $openid =$this->request->param('openid','','trim');
        $keyword =$this->request->param('keyword','','trim');
        $page =$this->request->param('page',1,'intval');
        $where =[];
        if($keyword){
            $where[]=['c.nickName','like','%'.$keyword.'%'];
        }
        $where[]=['m.openid','=',$openid];
        try{
            $user=(new MallUser())->alias('u')
                ->field('c.id,c.openid,c.nickName,c.avatarUrl,c.commission_level,u.nickName as fromNickName')
                ->join('mall_user m','m.id=u.id')
                ->join('mall_user c','c.parent_id=u.id')
                ->where($where)
                ->page($page,10)
                ->select()
                ->toArray();
            $count=(new MallUser())->alias('u')
                ->join('mall_user m','m.id=u.id')
                ->join('mall_user c','c.parent_id=u.id')
                ->where($where)
                ->count();
        }catch (\Exception $e){
            Log::error("user_update_save:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error, "查询失败");
        }
        $recnum =$count;
        if($user){
            foreach ($user as $k=>$v){
                if($v['commission_level']>0){
                    $levelinfo=(new MallCommissionLevel())->getlevelInfo($v['commission_level']);
                    $user[$k]['levelname'] =$levelinfo['levelname'];
                }else{
                    $user[$k]['levelname'] ='普通用户';
                }
                $orders=(new MallOrder())->field('id,ordersn,payprice')->where([['openid','=',$v['openid']],['orderstatus','in',[1,2,3]]])->select()->toArray();
                $user[$k]['ordercount'] = count($orders);
                $ordertotal = 0;
                if($orders){
                    foreach ($orders as $kk=>$vv){
                        $ordertotal+=$vv['payprice'];
                    }
                }
                $user[$k]['ordertotal'] =$ordertotal;
            }
        }
        return Show::json_show(Status::mini_normal, "ok",[
            'user'=>$user??[],
            'total'=>$recnum
        ]);
    }

    /**
     * 直推用户订单详情
     * @return \think\response\Json
     */
    public function myCommissionOrderDetail(){
        $openid =$this->request->param('openid','','trim');
        $uid =$this->request->param('uid','','intval');  // 下级会员用户id
        try{
            $minfo=(new MallUser())->getUserById($uid,'*');
            if($minfo){
                $order =(new MallOrder())->alias('o')
                    ->field('id,payprice,commission,FROM_UNIXTIME(paytime) as paytime')
                    ->where([['openid','=',$minfo['openid']],['orderstatus','in',[1,2,3]],['commission','>',0]])
                    ->select()
                    ->toArray();
            }
        }catch (\Exception $e){
            Log::error("user_update_save:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error, "查询失败");
        }
        if(empty($minfo)){
            return Show::json_show(Status::mini_error, "下级会员不存在");
        }
        if(empty($order)){
            return Show::json_show(Status::mini_error, "会员订单不存在");
        }
        foreach ($order as $k=>$v){
            $goods =(new MallOrderGoods())->getByOrderGoodsList($v['id'],'goods_name');
            $goodsnames ='';
            foreach ($goods as $kk=>$vv){
                $goodsnames.=$vv['goods_name'].' ';
            }
            $order[$kk]['goodsnames'] =$goodsnames;
        }

        return Show::json_show(Status::mini_normal, "ok",[
            'order'=>$order??[]
        ]);
    }


    /**
     * 我的团队
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function myteamUsers(){
        $openid =$this->request->param('openid','','trim');
        $keyword =$this->request->param('keyword','','trim');
        $page =$this->request->param('page',1,'intval');
        $where =[];
        if($keyword){
            $where[] =['c.nickName','like','%'.$keyword.'%'];
        }
        $where[]=['m.openid','=',$openid];
        try{
            $user=(new MallUser())->alias('u')
                ->field('c.id,c.openid,c.nickName,c.avatarUrl,c.commission_level,u.nickName as fromNickName')
                ->join('mall_user m','m.id=u.id')
                ->join('mall_user c','c.parent_id=u.id')
                ->where($where)
                ->page($page,10)
                ->select()->toArray();
            $count=(new MallUser())->alias('u')
                ->join('mall_user m','m.id=u.id')
                ->join('mall_user c','c.parent_id=u.id')
                ->where($where)
                ->count();
        }catch (\Exception $e){
            Log::error("user_update_save:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error, "查询失败");
        }
        $recnum =$count;
        if($user) {
            foreach ($user as $k => $v) {
                if ($v['commission_level'] > 0) {
                    $levelinfo = (new MallCommissionLevel())->getlevelInfo($v['commission_level']);
                    $user[$k]['levelname'] = $levelinfo['levelname'];
                } else {
                    $user[$k]['levelname'] = '普通用户';
                }
                $orders=(new MallOrder())->field('id,ordersn,payprice,againprice')->where([['openid','=',$v['openid']],['orderstatus','in',[1,2,3]]])->select()->toArray();
                $user[$k]['ordercount'] = count($orders);

                $ordertotal = 0;
                $againprice =0;
                if($orders){
                    foreach ($orders as $kk=>$vv){
                        $ordertotal+=$vv['payprice'];
                        $againprice+=$vv['againprice'];
                    }
                }
                $user[$k]['ordertotal'] =$ordertotal;
                // 团队奖励
                if($levelinfo){
                    $user[$k]['againprice'] =round($againprice*$levelinfo['commission_againpersont']/100,2);
                }else{
                    $user[$k]['againprice'] =0;
                }
            }
        }
        return Show::json_show(Status::mini_normal, "ok",[
            'user'=>$user??[],
            'total'=>$recnum
        ]);
    }

    /**
     * 佣金 推荐奖励
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getcommissionTypeList(){
        $openid =$this->request->param('openid','','trim');
        $type =$this->request->param('type',3,'intval');
        try{
            $result =(new MallUser())->getUserByList($openid,'id,nickName,avatarUrl,commission_level,level_time');
            $set=(new MallSetting())->getSettingInfo('teamset');
            if($result && $result['commission_level']>0){
                $commissionlevel =(new MallCommissionLevel())->getlevelInfo($result['commission_level']);
                $result['levelname'] =$commissionlevel['levelname'];
            }else{
                $result['levelname'] ='';
            }
        }catch (\Exception $e){
            Log::error("userinfo:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error, "发生错误");
        }
        if(empty($result)){
            return Show::json_show(Status::mini_error, "用户信息获取失败");
        }
        try{
            switch ($type){
                case 3:
                    // 直推所有订单
                    $orderscommission =(new MallOrder())->alias('o')
                        ->field('o.ordersn,o.id,o.payprice,FROM_UNIXTIME(o.paytime) as paytime,o.commission,u.nickName')
                        ->join('mall_user u','u.openid=o.openid')
                        ->where([['u.parent_id','=',$result['id']],['o.orderstatus','in',[1,2,3]],['o.commission','>',0]])
                        ->select()
                        ->toArray();

                    if($orderscommission){
                        foreach ($orderscommission as $kk=>$vv){
                            $goods =(new MallOrderGoods())->getByOrderGoodsList($vv['id'],'id,goods_name,total,image,price,option_name as get_specs_value');
                            $orderscommission[$kk]['child'] = $goods;
                        }
                    }
                    break;
                case 4:
                    // 直推所有订单
                    $orderscommission =(new MallOrder())->alias('o')
                        ->field('o.ordersn,o.id,o.payprice,FROM_UNIXTIME(o.paytime) as paytime,o.againprice as commission,u.nickName')
                        ->join('mall_user u','u.openid=o.openid')
                        ->where([['u.parent_id','=',$result['id']],['o.orderstatus','in',[1,2,3]],['o.againprice','>',0]])
                        ->select()
                        ->toArray();
                    if($orderscommission){
                        foreach ($orderscommission as $kk=>$vv){
                            $goods =(new MallOrderGoods())->getByOrderGoodsList($vv['id'],'id,goods_name,total,image,price,option_name as get_specs_value');
                            $orderscommission[$kk]['child'] = $goods;
                        }
                    }
                    break;
                case 5:
                    // 直推所有订单
                    $orderscommission =(new MallUser)
                        ->field('id,openid,commission_level,nickName,avatarUrl')
                        ->where([['parent_id','=',$result['id']]])
                        ->select()
                        ->toArray();
                    if($orderscommission){
                        foreach ($orderscommission as $kk=>$vv){
                            $linfo=(new MallCommissionLevel())->getlevelInfo($vv['commission_level']);
                            if($linfo){
                                $orderscommission[$kk]['levelname'] =$linfo['levelname'];
                            }else{
                                $orderscommission[$kk]['levelname'] ='普通用户';
                            }
                            $commissionagaintotal =(new MallOrder())->where([['openid','=',$vv['openid']],['orderstatus','in',[1,2,3]],['againprice','>',0]])->sum('againprice');
                            if($set){
                                $orderscommission[$kk]['commission_team'] = round($commissionagaintotal*$set['option_value']/100,2);
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }catch (\Exception $e){
            Log::error("userinfo:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error, $e->getMessage());
        }

        return Show::json_show(Status::mini_normal, "ok",[
            'user'=>$orderscommission??[]
        ]);
    }



    /**
     * 用户提现参数信息
     * @return \think\response\Json
     */
    public function getWithdrawal(){
        $openid =$this->request->param('openid','','trim');
        try{
            $list = (new MallSetting())->getSetting(['balance','withdrawal']);
            $member =(new MallUser())->getUserByList($openid,'id,balance,againbalance,teambalance');
        }catch (\Exception $e){
            Log::error("getsetting:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(empty($list)){
            return Show::json_show(Status::mini_error,'系统配置错误');
        }
        if(empty($member)){
            return Show::json_show(Status::mini_error,'用户信息错误');
        }

        foreach ($list as $k=>$v){
            if($v['name'] =='balance'){
                $member['balanceset'] =$v['option_value'];
            }
            if($v['name'] =='withdrawal'){
                $member['withdrawalset'] =$v['option_value'];
            }
        }
        return Show::json_show(Status::mini_normal, "ok",[
            'setting'=>$member
        ]);
    }

    /**
     * 提现处理
     * @return \think\response\Json
     */
    public function doWithdrawal(){
        $openid =$this->request->param('openid','','trim');
        $type =$this->request->param('type','3','intval');
        $money =$this->request->param('money','','trim');
        $realname =$this->request->param('realname','','trim');
        $mobile =$this->request->param('mobile','','trim');
        if (!$money || !$realname || !$mobile) {
            return Show::json_show(Status::mini_error, '请输入提现信息');
        }
        if (!preg_match('/^(?:(?:\+|00)86)?1[3-9]\d{9}$/', $mobile)) {
            return Show::json_show(Status::mini_error, '请输入正确的手机号');
        }
        try{
            $list = (new MallSetting())->getSetting(['balance','withdrawal']);
            $member =(new MallUser())->getUserByList($openid,'id,balance,againbalance,teambalance');
        }catch (\Exception $e){
            Log::error("getsetting:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(empty($list)){
            return Show::json_show(Status::mini_error,'系统配置错误');
        }
        if(empty($member)){
            return Show::json_show(Status::mini_error,'用户信息错误');
        }
        foreach ($list as $k=>$v){
            if($v['name'] =='balance'){ //  满额
                $member['balanceset'] =$v['option_value'];
            }
            if($v['name'] =='withdrawal'){ // 提额
                $member['withdrawalset'] =$v['option_value'];
            }
        }
        switch ($type){
            case 3:
                if($money>$member['balance'] || $money<$member['balanceset'] || $money%$member['withdrawalset']!=0){
                    return Show::json_show(Status::mini_error,'提现不合法，请稍后重试');
                }
                break;
            case 4:
                if($money>$member['againbalance'] || $money<$member['balanceset'] || $money%$member['withdrawalset']!=0){
                    return Show::json_show(Status::mini_error,'提现不合法，请稍后重试');
                }
                break;
            case 5:
                if($money>$member['teambalance'] || $money<$member['balanceset'] || $money%$member['withdrawalset']!=0){
                    return Show::json_show(Status::mini_error,'提现不合法，请稍后重试');
                }
                break;
            default:
                break;
        }
        $model =(new MallWithdrawal());
        switch ($type){
            case 3:
                $typedesc='推荐奖提现';
                break;
            case 4:
                $typedesc='业绩奖提现';
                break;
            case 5:
                $typedesc='团队奖提现';
                break;
            default:
                break;
        }
        try{
            $data =array(
                'openid' =>$openid,
                'money' =>$money,
                'realname' =>$realname,
                'mobile' =>$mobile,
                'type'   =>$type,
                'typedesc'   =>$typedesc,
                'status' =>0,
                'ordersn'=>Str::RandomStr(),
                'datetime' =>date('Y-m-d')
            );
            $save=$model->save($data);

            switch ($type){
                case 3:
                    (new MallUser())->where("openid",'=',$openid)->Dec('balance',$money)->update();
                    break;
                case 4:
                    (new MallUser())->where("openid",'=',$openid)->Dec('againbalance',$money)->update();
                    break;
                case 5:
                    (new MallUser())->where("openid",'=',$openid)->Dec('teambalance',$money)->update();
                    break;
                default:
                    break;
            }



            // 开始处理提现
//            $objClass = ArrClass::payAttr();
//            $obj = ArrClass::initClass('wx', $objClass, [], true);
//            // 提现接口
//            $notify= $obj->transfer([
//                'partner_trade_no' => $data['ordersn'], // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
//                'openid' => $openid,
//                'check_name' => 'FORCE_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
//                're_user_name' => $realname, // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
//                'amount' => $money*100, // 企业付款金额，单位为分
//                'desc' => '共享商城提现', // 企业付款操作说明信息。必填
//            ]);
//            if($notify && $notify['return_code'] == 'SUCCESS'){
//                if($notify['result_code'] == 'SUCCESS'){
//                    $model->where("ordersn",$data['ordersn'])->save(array('status'=>1));
//                    (new MallAccountLog())->saveAccoutLog($openid,$money,2,'会员提现');
//                }else{
//                    return Show::json_show(Status::mini_error,$notify['err_code_des']);
//                }
//            }
//            else{
//                return Show::json_show(Status::mini_error,'提现失败');
//            }
        }catch (\Exception $e){
            Log::error("getsetting:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error,'查询失败');
        }
        return Show::json_show(Status::mini_normal, "ok",[
        ]);
    }

    /**
     * 提现记录
     * @return \think\response\Json
     */
    public function myWithdrawalList(){
        $openid =$this->request->param('openid','','trim');
        try{
            $list=(new MallWithdrawal())->field('id,typedesc,money,status,create_time')->where("openid",'=',$openid)->order('create_time desc')->select()->toArray();
        }catch (\Exception $e){
            Log::error("getsetting:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if($list){
            foreach ($list as $k=>$v){
                switch ($v['status']){
                    case 0:
                        $list[$k]['statusname'] ='审核中';
                        break;
                    case 1:
                        $list[$k]['statusname'] ='已提现';
                        break;
                    case 2:
                        $list[$k]['statusname'] ='拒绝提现';
                        break;
                    default:
                        break;
                }
            }
        }
        return Show::json_show(Status::mini_normal, "ok",[
            'list' =>$list
        ]);
    }
}